package com.example.yls.demoa;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements EventListening {

    private ListView lvStu;
    private List<Student> stuList;
    private Button addBtn;
    private StuAdapter stuAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lvStu = findViewById(R.id.lv_stu);
        addBtn = findViewById(R.id.btn_add);

        stuList = new ArrayList<>();

        initstuList();

        stuAdapter = new StuAdapter(this,this,stuList);
        lvStu.setAdapter(stuAdapter);

        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,AddActivity.class);
                startActivityForResult(intent,101);
            }
        });

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 101:
                int headImgId = data.getIntExtra("imgId", R.drawable.dog1);
                String name = data.getStringExtra("name");
                int age = data.getIntExtra("age",0);

                Student student = new Student(headImgId,name,age);
                stuList.add(student);
                stuAdapter.notifyDataSetInvalidated();

                break;
        }
    }

    private void initstuList() {

        Student student1 = new Student(R.drawable.dog1,"小黄",4);
        Student student2 = new Student(R.drawable.dog2,"小黄",4);
        Student student3 = new Student(R.drawable.dog3,"小黄",4);
        Student student4 = new Student(R.drawable.dog4,"小黄",4);
        Student student5 = new Student(R.drawable.dog5,"小黄",4);

        stuList.add(student1);
        stuList.add(student2);
        stuList.add(student3);
        stuList.add(student4);
        stuList.add(student5);
        stuList.add(student1);
        stuList.add(student2);
        stuList.add(student3);
        stuList.add(student4);
        stuList.add(student5);
        stuList.add(student1);
        stuList.add(student2);
        stuList.add(student3);
        stuList.add(student4);
        stuList.add(student5);
        stuList.add(student1);
        stuList.add(student2);
        stuList.add(student3);
        stuList.add(student4);
        stuList.add(student5);

    }

    @Override
    public void delete(int index) {
        stuList.remove(index);
        stuAdapter.notifyDataSetChanged();
    }
}
